var httpsUrl = getApp().globalData.httpsUrl;
var globalData = getApp().globalData;
var commonUtil = require("../../../utils/commonUtil.js")
var WxParse = require("../../../wxParse/wxParse.js")
Page({
  data: {
    imgUrl: globalData.imgUrl,
    info:[],
    content: "",
    registerFlag: 0,// 0不展示授权信息 1展示
    phoneFlag: 0,//0不展示手机授权  1展示
  },
  goodsInfo:function(){
    var that = this;
    var params = new Object();
    params.code = wx.getStorageSync("goodsCode");
    let openId = wx.getStorageSync("openidKey");
    console.log("param:" + JSON.stringify(params));
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/goods/getGoodsDetailByCode",
      dataType: "json",
      method: "GET",
      data: params,
      success: function (res) {
        res = res.data;
        console.log("res：" + JSON.stringify(res));
        if (res.result == 0) {
          that.setData({ info: res.data })
          that.commission();
          let xq = res.data.describe;
          if (!commonUtil.isEmpty(xq)){
            var content = '<div>' + xq + '</div>';
            let contentTemp = WxParse.wxParse('content', 'html', content, that, 5);//(变量名，代码类型，代码内容，当前this，imagePadding)
            // that.setData({ content: contentTemp })
          }
        }
      }
    })
  },
  commission: function () {
    var that = this;
    let info = this.data.info;
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/goodsCommission/getCommission",
      dataType: "json",
      method: "POST",
      data: { "goodsNo": info.code },
      success: function (res) {
        res = res.data;
        console.log("佣金：" + JSON.stringify(res));
        if (res.result == 0) {
          info.commissionStr = res.data;
          that.setData({ info: info })
        }
      }
    })
  },
  submitOrder:function(){
    let info = this.data.info;
    info.count = 1;
    let payGoods = [];
    payGoods = payGoods.concat(info);
    wx.setStorageSync("payGoods", payGoods);
    wx.navigateTo({
      url: '../../order/submitOrder/submitOrder',
    })
  },
  homepage: function () {
    wx.switchTab({url: '../../homepage/homepage/homepage',})
  },
  shopInfo: function (e) {
    let info = this.data.info;
    wx.setStorageSync("businessCode", info.businessCode)
    wx.navigateTo({url: '../shopInfo/shopInfo',})
  },
  onLoad: function (options) {
    console.log("options:" + JSON.stringify(options));
    if (options.goodsCode != undefined && options.goodsCode != null && options.goodsCode != '') {
      wx.setStorageSync("goodsCode", options.goodsCode);
      wx.setStorageSync("parentCode", options.parentCode);
    }
    this.getOpenId();
  },
  onShareAppMessage: function (options) {
    var goodsCode = wx.getStorageSync("goodsCode");
    var user = this.data.user;
    //分享参数包
    var shareObj = {
      title: "",
      path: '/pages/shop/goodsInfo/goodsInfo?goodsCode=' + goodsCode + '&parentCode=' + user.member_no, // 默认是当前页面，必须是以‘/’开头的完整路径
      imgUrl: '',
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') { }
      },
      fail: function (res) {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          // 用户取消转发
        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败，其中 detail message 为详细失败信息
        }
      },
      complete: function () {
        // 转发结束之后的回调（转发成不成功都会执行）
      }
    };
    // 来自页面内的按钮的转发
    if (options.from == 'button') {
      // var eData = options.target.dataset;
      //shareObj.path = '/pages/btnname/btnname?btn_name=' + eData.name;
    }
    console.info("分享参数包:" + JSON.stringify(shareObj));
    return shareObj;
  },
  //用户信息检验,若不存在，则授权,若已存在判断手机号
  getOpenId: function () {
    let that = this;
    wx.login({
      success: function (res) {
        wx.showLoading({ title: '请稍等...', })
        wx.request({
          header: { "content-Type": "application/x-www-form-urlencoded" },
          url: httpsUrl + "/wechat/getOpenId",
          dataType: "json",
          method: "POST",
          data: { "code": res.code, "agentCode": globalData.agentCode },
          success: function (res) {
            wx.hideLoading();
            res = res.data;
            console.log("获取openid返回:" + JSON.stringify(res));
            if (res.result == 0) {
              let data = JSON.parse(res.data);
              wx.setStorageSync("openidKey", data.openid);
              wx.setStorageSync("sessionKey", data.session_key);
              console.log("openid:" + data.openid);
              that.searchUser();
            } else {
              console.log("获取openid失败：" + res.msg);
            }
          }
        })
      }
    })
  },
  //查询用户信息
  searchUser: function () {
    let that = this;
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/member/info",
      dataType: "json",
      method: "GET",
      // data: { "openId": data.openid },
      success: function (res) {
        res = res.data;
        console.log("userInfo:" + JSON.stringify(res));
        if (res.result == 0) {
          that.goodsInfo();
          var user = res.data;
          that.setData({ user: user })
          if (commonUtil.isEmpty(user.phone)) {
            that.setData({ phoneFlag: 1 })
          }
        } else if (res.result == 2) {
          that.setData({ registerFlag: 1 })//{"result":2,"msg":"用户未注册!","data":null}
        }
      }
    })
  },
  //授权信息
  getUserInfo: function (e) {
    var that = this;
    //会弹框询问是否授权，拒绝则得到undefined
    //console.log("wxinfo:" + JSON.stringify(e.detail.userInfo));
    let info = e.detail.userInfo;
    if (!commonUtil.isEmpty(info)) {
      var params = new Object();
      params.openId = wx.getStorageSync("openidKey");
      params.nick = info.nickName;
      params.sex = info.gender;//性别 1 男，2 女，0未知
      params.img = info.avatarUrl;//头像
      params.country = info.country;
      params.provice = info.province;
      params.city = info.city;
      // params.unionId = this.data.unionId;
      params.agentCode = globalData.agentCode;//代理商编码，小程序固定值
      params.parentCode = wx.getStorageSync("parentCode");//推荐用户编码
      //params.businessCode = wx.getStorageSync("businessCode");//商家编码
      console.log("注册params:" + JSON.stringify(params));
      commonUtil.showLoading("请稍等...");
      wx.request({
        // header: {"content-Type": "application/x-www-form-urlencoded" },
        url: httpsUrl + "/regist?parentCode=" + params.parentCode,
        dataType: "json",
        method: "POST",
        data: params,
        success: function (result) {
          commonUtil.hideLoading();
          var res = result.data;
          console.log("注册返回：" + JSON.stringify(res));
          if (res.result == 0) {
            commonUtil.showSuccessToast("注册成功");
            that.setData({ registerFlag: 0 })
            that.searchUser();
          } else {
            commonUtil.showModal("注册失败！" + res.message);
          }
        }
      })
    }
  },
  //手机号授权获取
  getphonenumber: function (e) {
    this.setData({ phoneFlag: 0 })
    //console.log("encryptedData:" + JSON.stringify(e.detail.encryptedData));
    if (commonUtil.isEmpty(e.detail.encryptedData)) {
      return;
    }
    let that = this;
    var params = new Object();
    params.encryptedData = e.detail.encryptedData;
    params.iv = e.detail.iv;
    // params.code = wx.getStorageSync("code");
    params.sessionKey = wx.getStorageSync("sessionKey");
    console.log("手机解密参数：" + JSON.stringify(params));
    wx.request({
      header: { "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/wechat/xcxUserPhone",
      dataType: "json",
      method: "GET",
      data: params,
      success: function (result) {
        var res = result.data;
        console.log("解密结果：" + JSON.stringify(res));
        if (res.result == 0) {
          let data = JSON.parse(res.data);
          let phone = data.phoneNumber;
          console.log(phone);
          commonUtil.updatePhoneByWechat(phone);
        }
      }
    })
  }
})